package com.dusk.util
{
	import flash.crypto.generateRandomBytes;
	import flash.utils.ByteArray;
	
	public final class RandomUtil extends UtilBase
	{
		/**
		 * 返回目标内随机小数
		 * @param lowThreshold 下限
		 * @param highThreshold 上限
		 * @param decimal 目标保留小数
		 * @return 随机数
		 */
		public static function randNum(lowThreshold:Number = 0,highThreshold:Number = 1,decimal:int = 2):Number
		{
			if(decimal < 0)
			{
				throw new Error("arguments Error, decimal should be more than 0");
			}
			if(lowThreshold >= highThreshold)
			{
				throw new Error("arguments Error, lowThreshold should be less than highThreshold");
			}
			return MathUtil.decimal(lowThreshold + Math.random() * (highThreshold - lowThreshold), decimal);
		}
		
		/**
		 * 返回范围内随机整数
		 * @param lowThreshold 下限
		 * @param highThreshold 上限
		 * @return 随机数
		 */
		public static function randInt(lowThreshold:Number = 0,highThreshold:Number = 10):int
		{
			if(lowThreshold >= highThreshold)
			{
				throw new Error("arguments Error, lowThreshold should be less than highThreshold");
			}
			return Math.round(lowThreshold + Math.random() * (highThreshold - lowThreshold));
		}
		
		/**
		 * 获取随机色值
		 * @return 返回色值号
		 */
		public static function randColor():uint
		{
			return Math.random() * 0xFFFFFF;
		}
		
		/**
		 * 获取指定长度的随机字节数组
		 * @param length 指定随机数组长度
		 * @return 随机数组
		 */
		public static function randBytes(length:uint):ByteArray
		{
			return generateRandomBytes(length);
		}
		
		/**
		 * 从数组中随机选取一个对象并返回该对象
		 * @param	arr			目标数组
		 * @param	weightArr	数组中每一项的权值，权值越高被选中的概率越大，该数组长度必须和目标数组一致，默认设置为 null 选取到每一项的概率一致
		 * @return	随机选取出的对象
		 */
		public static function randSwitch(arr:Array, weightArr:Array = null):*
		{
			if (!arr.length) return null;
			if (!weightArr) {
				return arr[Math.floor(Math.random() * arr.length)];
			}
			var totVal:Number = 0;
			for (var i:int = 0; i < weightArr.length; ++i)
			{
				totVal += weightArr[i];
			}
			var randVal:Number = Math.random() * totVal;
			totVal = 0;
			for (var j:int = 0; j < weightArr.length; ++j)
			{
				totVal += weightArr[j];
				if (randVal < totVal) return arr[j];
			}
			return null;
		}
		
		/**
		 * 按照概率返回布尔值
		 * <br>示例</br>
		 * randBoolean(30) 即为30%的概率返回true
		 * @param possibility 概率，整数
		 * @return true or false
		 *
		 */
		public static function randBoolean(possibility:int = 50):Boolean
		{
			if (possibility >= 100)
			{
				return true;
			}
			if (possibility < 0)
			{
				return false;
			}
			return Math.round(Math.random() * 100) <= possibility;
		}
	}
}
